1528A - Parsa's Humongous Tree - CodeForces Solution


dfs and similar divide and conquer dp greedy trees *1600

Please click on ads to support us..

C++ Code:

#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf = 1e9+7;
vector <int> v[1000001];
ll dp[1000001][2];
ll vis[1000001];
ll l[1000001],r[1000001];
ll n;
void dfs (ll u) 
{
	vis[u]=1;
	for (int i:v[u]) 
    {
		if (vis[i]==0) 
		{
			dfs(i);
			dp[u][0]+=max(dp[i][0]+abs(l[i]-l[u]),dp[i][1]+abs(r[i]-l[u]));
			dp[u][1]+=max(dp[i][0]+abs(l[i]-r[u]),dp[i][1]+abs(r[i]-r[u]));
		}
	}
}

int main () {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	ll t; 
	cin >> t;
	while (t--) 
    {
		cin >> n;
		for (int i=1;i<=n;i++) 
        {
			vis[i]=0;
			v[i].clear();
			cin >> l[i] >> r[i];
			dp[i][0]=0;
			dp[i][1]=0;
		}
		for (int i=1;i<n;i++) 
		{
		    ll x, y;
			cin >> x >> y;
			v[x].push_back(y);
			v[y].push_back(x);
		}
		dfs(1);
		cout << max(dp[1][0],dp[1][1]) << endl;
	}	
}
  		    	 						       	  				


Comments

Submit
0 Comments
More Questions

1634B - Fortune Telling
1358A - Park Lighting
253C - Text Editor
365B - The Fibonacci Segment
75A - Life Without Zeros
1519A - Red and Blue Beans
466A - Cheap Travel
659E - New Reform
1385B - Restore the Permutation by Merger
706A - Beru-taxi
686A - Free Ice Cream
1358D - The Best Vacation
1620B - Triangles on a Rectangle
999C - Alphabetic Removals
1634C - OKEA
1368C - Even Picture
1505F - Math
1473A - Replacing Elements
959A - Mahmoud and Ehab and the even-odd game
78B - Easter Eggs
1455B - Jumps
1225C - p-binary
1525D - Armchairs
1257A - Two Rival Students
1415A - Prison Break
1271A - Suits
259B - Little Elephant and Magic Square
1389A - LCM Problem
778A - String Game
1382A - Common Subsequence